<?php
/**
 * 处理Cors跨域
 */

namespace support\middleware;

use think\Request;
use think\Response;
use think\MiddlewareInterface;


class AccessCors implements MiddlewareInterface
{

    public function process(Request $request, callable $next): Response
    {
        $origin = '*';
        if (!empty(C('web_url'))) {
            $allowUrl = explode(',', C('web_url'));
            $httpOrigin = !empty($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
            if (in_array($httpOrigin, $allowUrl)) {
                $origin = $httpOrigin;
            }
        }

        $header = [
            'Access-Control-Allow-Origin' => $origin,
            'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE',
            'Access-Control-Allow-Credentials' => true,
            'Access-Control-Allow-Headers' => 'Authorization, Content-Type, Token, X-Userinfo, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With,Accept,Origin, Device-Unique-Code',
        ];


        // 处理跨域请求
        if ($request->method() == 'OPTIONS') {
            $response = Response::create()->code(204)->header($header);
        } else {
            $response = $next($request);
        }

        return $response;
    }

}
